/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.jdbc.utils;

import java.util.ArrayList;
import java.util.List;

import com.iiifi.kite.jdbc.model.BaseTreeModel;

/**
 * TreeConvert
 *
 * @author ii@iiifi.com 花朝
 */
public class TreeConvert<E extends BaseTreeModel<E>> {

    public List<E> convertTree(List<E> list) {
        // 根节点
        List<E> rootMenu = new ArrayList<>();
        for (E nav : list) {
            // 父节点是0的，为根节点。
            if (nav.getParentId() == -1) {
                nav.setParentName("/");
                rootMenu.add(nav);
            }
        }
        // 为根菜单设置子菜单，getClild是递归调用的
        for (E nav : rootMenu) {
            /* 获取根节点下的所有子节点 使用getChild方法 */
            List<E> childList = getChild(nav, list);
            // 给根节点设置子节点
            nav.setChildren(childList);
        }
        return rootMenu;
    }

    /**
     * 获取子节点
     *
     * @param model model
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    private List<E> getChild(BaseTreeModel<E> model, List<E> allMenu) {
        // 子菜单
        List<E> childList = new ArrayList<>();
        for (E nav : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            // 相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(model.getId())) {
                nav.setParentName(model.getName());
                childList.add(nav);
            }
        }
        // 递归
        for (E nav : childList) {
            nav.setChildren(getChild(nav, allMenu));
        }
        // 如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
